package com.woniu.consume;

import com.alibaba.fastjson2.JSON;
import com.rabbitmq.client.Channel;
import com.woniu.entity.SecKillBook;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class DelSecKillConsume {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @RabbitListener(queues = "delSecKill")
    public void receive(String msg, Message message, Channel channel){

        try {
            //把传过来的JSON字符串，转成对象
            SecKillBook secKillBook = JSON.parseObject(msg, SecKillBook.class);
            //从秒杀表删除，但是暂时只删除 redis
            //secKillMapper.addKillBook(secKillBook);
            redisTemplate.opsForHash().delete("seckillBook", secKillBook.getBookId() + "");
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
